const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

/**
 * 封封微信的的request
 */
function request(method, url, data = {}) {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.statusCode == 200) {
          // token失效 跳转登录
          if (res.data.code === '603' && wx.getStorageSync('CampusAssistant-Islogin')) {
            wx.removeStorageSync('CampusAssistant-token')
            wx.setStorageSync('CampusAssistant-Islogin', false)
            wx.navigateTo({
              url: '/pages/subpackage/wxlogin/index'
            });
            return;
          } else {
            resolve(res.data);
          }
        } else {
          var errMsg = '请求异常';
          switch (res.statusCode) {
            case 404: 
              errMsg = `接口异常`;
              break;
          }
          if (res.statusCode) {
            errMsg += '-' + res.statusCode;
          }
          wx.showToast({
            title: errMsg,
            icon: 'none'
          })
          wx.hideLoading()
          reject(res.errMsg);
        }

      },
      fail: function (er) {
        wx.hideLoading()
        var errMsg = '请求异常';
        switch (er.errMsg) {
					case 'request:fail':
						errMsg = '网络异常，请检查网络';
						break;
          case 'request:fail timeout':
            errMsg = '网络超时，请稍后再试';
            break;
          case 'request:fail 请求失败':
            errMsg = '请求失败，请稍后再试';
            break;
          case 'request:fail interrupted':
            errMsg = '网络异常，请检查网络';
            break;
          case 'request:fail 无法解析域名':
            errMsg = '网络地址错误，请检查地址';
            break;
          default:
            errMsg = '未知错误，请稍后再试';
        }
        if (er.errno) {
          errMsg += '-' + er.errno;
        }
        wx.showToast({
          title: errMsg,
          icon: 'none'
        })
        reject(er)
      }
    })


  });
}

// 手机号校验
function isPhoneNumberValid(phoneNumber) {
  const regex = /^1[3456789]\d{9}$/; // 正则表达式，匹配1开头，第二位为3-9的任意数字，后面跟9位数字的手机号
  return regex.test(phoneNumber);
}

/**
 * 调用微信登录
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          //登录远程服务器
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

function getUserInfo() {
  return new Promise(function (resolve, reject) {
    const app = getApp();
     const user = app.getSessionUser();
     if(user == null){
        reject(null);
     }else{
         resolve({
           "userInfo" : user
         });
     }

  });
}

// 密码校验
function validatePassword(password) {
  const regex = /^[a-zA-Z0-9]{8}$/;
  return regex.test(password);
}

function timeChangeover (time) {
  let parts = time.split(' ');
  parts[1] = parts[1].substring(0, 5)
  // 获取当前日期
  let currentDate = new Date();
  // 存放日期的数组
  let dates = [];
  // 获取近三天的日期
  for (let i = 0; i < 3; i++) {
    let date = new Date(currentDate.getTime() + i * 24 * 60 * 60 * 1000);
    dates.push(formatDate(date));
  }
  switch (parts[0]) {
    case dates[0]:
      return '今天 ' + parts[1]
      break;
    case dates[1]:
      return '明天 ' + parts[1]
      break;
    case dates[2]:
      return '后天 ' + parts[1]
      break;
    default:
      return parts[0] + ' ' + parts[1]
      break;
  }
}

// 格式化日期为年-月-日
function formatDate(date) {
  let year = date.getFullYear();
  let month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
  let day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
// 时间判断 是否在1小时内 还是1小时外
function isWithinOneHour(targetTime) {
  console.log(targetTime);
  const now = new Date();
  const targetDate = new Date(targetTime);

  // 计算目标时间和当前时间的差值（毫秒）
  const diff = targetDate - now;
  // 判断是否在1小时内
  if (diff <= 0) {
    return true
  }else if (diff <= 3600000) {
    return true
  } else {
    return false
  }
}

function isValidChineseLicensePlate(plate) {
  // 正则表达式
  let data = plate.trim().replace(/\s+/g, '')
//   const regex = /^(?:[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[0-9A-Z]{6})$/;
  const regex = /^((^(京|津|沪|渝|冀|豫|云|辽|黑|湘|皖|鲁|新|苏|浙|赣|鄂|桂|甘|晋|蒙|陕|吉|闽|贵|粤|青|藏|川|宁|琼)[A-Z]{1}[A-Z0-9]{5}[A-Z0-9挂学警港澳试超使领北南军海空外]{1}$)|(^(京|津|沪|渝|冀|豫|云|辽|黑|湘|皖|鲁|新|苏|浙|赣|鄂|桂|甘|晋|蒙|陕|吉|闽|贵|粤|青|藏|川|宁|琼)[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳试超使领北南军海空外]{1}$))$/;
  return regex.test(data);

}

module.exports = {
  formatTime,
  request,
  isPhoneNumberValid,
  login,
  getUserInfo,
  validatePassword,
  timeChangeover,
  isWithinOneHour,
  isValidChineseLicensePlate
}
